package com.example.administrator.myapplication;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class SelectImageActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private ImagesListAdapter mAdapter;
    private ArrayList<ImageBean> mData = new ArrayList<>();
    private int maxsize = 9;
    private int minSize = 1;
    private List<ImageBean> mTempImageBeans;
    private List<LocalMedia> mSelectLocalList = new ArrayList<>();
    private List<String> deleteIds = new ArrayList<>();
    //获取用户已经上传的图片
    private List<ImageBean> mImagesWithNetUrl = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_image);
        mRecyclerView = findViewById(R.id.recycler);
        final GridLayoutManager layoutManager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new ImagesListAdapter(R.layout.gv_filter_image, mData);
        mAdapter.setSelectMax(maxsize);
        mAdapter.setOnAddPicClickListener(new ImagesListAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                openGallery();
            }
        });
        mAdapter.setOnItemClicklistener(position -> {
            //预览图片
            //PictureSelector.create(SelectImageActivity.this).externalPicturePreview(position, mSelectList);
        });
        //删除
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                if (position != RecyclerView.NO_POSITION) {
//                    if (mSelectLocalList!=null&&mSelectLocalList.size()>0){
//                        mSelectLocalList.remove(adapter.getData().size());
//                    }
                    ImageBean imageBean = (ImageBean) adapter.getItem(position);
                    if (imageBean.getImageNet() != null) {
//                        int id = imageBean.getImageNet().getId();
//                        Log.d("deleteId", imageBean.getImageNet().getId() + "");
//                        deleteIds.add(imageBean.getImageNet().getId() + "");
//                        mAdapter.getData().remove(position);
//                        mAdapter.notifyItemRemoved(position);
//                        mAdapter.notifyItemRangeChanged(position, adapter.getData().size());
                        showDeletePrompt(adapter, position, imageBean);
                    } else {
                        if (mSelectLocalList.size() > 0) {
                            if (mImagesWithNetUrl.size() > 0) {
                                mSelectLocalList.remove(position - mImagesWithNetUrl.size());
                            } else {
                                mSelectLocalList.remove(position);
                            }
                        }
                        mAdapter.getData().remove(position);
                        mAdapter.notifyItemRemoved(position);
                        mAdapter.notifyItemRangeChanged(position, adapter.getData().size());
                    }
//                    if (mImagesWithNetUrl != null && mImagesWithNetUrl.size() > 0) {
//                        if (imageBean.getImageNet()!=null){
//                            int id = imageBean.getImageNet().getId();
//                            Log.d("deleteId", imageBean.getImageNet().getId() + "");
//                            deleteIds.add(imageBean.getImageNet().getId() + "");
//                            mAdapter.getData().remove(position);
//                            mAdapter.notifyItemRemoved(position);
//                            mAdapter.notifyItemRangeChanged(position, adapter.getData().size());
//                        }else {
//                            mAdapter.getData().remove(position);
//                            mAdapter.notifyItemRemoved(position);
//                            mAdapter.notifyItemRangeChanged(position, adapter.getData().size());
//                        }
//                    } else {
//                        mAdapter.getData().remove(position);
//                        mAdapter.notifyItemRemoved(position);
//                        mAdapter.notifyItemRangeChanged(position, adapter.getData().size());
////                    }
//                    }
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        getImageDataByNet();
    }

    /*
     * 弹出删除提示框
     */
    private void showDeletePrompt(final BaseQuickAdapter adapter, final int position, final ImageBean imageBean) {

        new AlertDialog.Builder(SelectImageActivity.this)
                .setMessage("确定删除吗?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        int id = imageBean.getImageNet().getId();
                        Log.d("deleteId", imageBean.getImageNet().getId() + "");
                        deleteIds.add(imageBean.getImageNet().getId() + "");
                        mImagesWithNetUrl.remove(position);
                        mAdapter.getData().remove(position);
                        mAdapter.notifyItemRemoved(position);
                        mAdapter.notifyItemRangeChanged(position, adapter.getData().size());
                    }
                }).setNegativeButton("取消", null).show();
//
    }

    private void getImageDataByNet() {

        final ImageBean imageBean1 = new ImageBean();
        final ImageBean.ImageNet imageNet1 = new ImageBean.ImageNet("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1520776039998&di=9a75488486704ef8e1d1ce7016bde0da&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dpixel_huitu%252C0%252C0%252C294%252C40%2Fsign%3Dc9d9632d69d0f703f2bf9d9c61823451%2Feaf81a4c510fd9f994e060532e2dd42a2834a410.jpg", 1);
        imageBean1.setImageNet(imageNet1);
        mImagesWithNetUrl.add(imageBean1);
        final ImageBean imageBean2 = new ImageBean();
        final ImageBean.ImageNet imageNet2 = new ImageBean.ImageNet("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1521370966&di=c56da87a193e99194ef95b28c86ef577&imgtype=jpg&er=1&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dshijue1%252C0%252C0%252C294%252C40%2Fsign%3Dee4843fd49a98226accc2364e2ebd374%2Fcefc1e178a82b9014f1c02bb798da9773812ef81.jpg", 2);
        imageBean2.setImageNet(imageNet2);
        mImagesWithNetUrl.add(imageBean2);
        final ImageBean imageBean3 = new ImageBean();
        final ImageBean.ImageNet imageNet3 = new ImageBean.ImageNet("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3990209058,403613144&fm=200&gp=0.jpg", 3);
        imageBean3.setImageNet(imageNet3);
        mImagesWithNetUrl.add(imageBean3);
        mData.addAll(mImagesWithNetUrl);
        mAdapter.setSelectMax(maxsize);
        mAdapter.setNewData(mData);
        mAdapter.openLoadAnimation();
    }

    private void openGallery() {
// 进入相册 以下是例子：不需要的api可以不写
        PictureSelector.create(SelectImageActivity.this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                //.theme(R.style.picture_white_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(maxsize-mImagesWithNetUrl.size())// 最大图片选择数量
                .minSelectNum(minSize)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .previewVideo(false)// 是否可预览视频
                .enablePreviewAudio(false) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .selectionMedia(mSelectLocalList)
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                //.compressSavePath(getPath())//压缩图片保存地址
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                // .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                .isGif(false)// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .openClickSound(false)// 是否开启点击声音
                //.selectionMedia(mSelectLocalList)// 是否传入已选图片
                .compressSavePath(getPath())//压缩图片保存地址
                .isDragFrame(true)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                .rotateEnabled(true) // 裁剪是否可旋转图片
                .scaleEnabled(true)// 裁剪是否可放大缩小图片
                //.videoQuality()// 视频录制质量 0 or 1
                //.videoSecond()//显示多少秒以内的视频or音频也可适用
                //.recordVideoSecond()//录制视频秒数 默认60s
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    /**
     * 自定义压缩存储地址
     *
     * @return
     */
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    Log.i("uploadImage", "md:" + mAdapter.getData().size() + "");
                    Log.i("uploadImage", "mimag:" + mImagesWithNetUrl.size() + "");
                    final int selectLocalsize = mSelectLocalList.size();
                    final int imageNetSize = mImagesWithNetUrl.size();
                    //int i1 = selectLocalsize + imageNetSize;

//                    for (int i = mImagesWithNetUrl.size(); i < mAdapter.getData().size(); i++) {
//                        Log.i("uploadImage", "position"+i);
//                        mAdapter.getData().remove(i);
//                        mAdapter.notifyItemRemoved(i);
//                        mAdapter.notifyItemRangeChanged(0, mAdapter.getData().size());
//                    }
//                    if (mSelectLocalList.size()>0){
//                        mAdapter.remove(mAdapter.getData().size()-1);
//                        mAdapter.notifyItemRemoved(mAdapter.getData().size()-1);
//                        mAdapter.notifyItemRangeChanged(0, mAdapter.getData().size());
//                    }
                    Log.i("uploadImage", "md:" + mAdapter.getData().size() + "");
                 mData.clear();
                 mData.addAll(mImagesWithNetUrl);
                    // 图片选择结果回调
                    mSelectLocalList = PictureSelector.obtainMultipleResult(data);
                    Log.i("uploadImage", "ms:" + mSelectLocalList.size());
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    if (mTempImageBeans == null) {
                        mTempImageBeans = new ArrayList<>();
                    } else {
                        mTempImageBeans.clear();
                    }
                    for (int i = 0; i < mSelectLocalList.size(); i++) {
                        ImageBean imageBean = new ImageBean();
                        imageBean.setLocalMedia(mSelectLocalList.get(i));
                        mData.add(imageBean);
                    }
                    // mData.addAll(mAdapter.getData().size(), mTempImageBeans);

                    mAdapter.setNewData(mData);
                    mAdapter.notifyItemRangeChanged(mImagesWithNetUrl.size(),mAdapter.getData().size());

                    break;
                default:
                    break;
            }
        }
    }
}
